package com.sh.data.engine.util;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/* loaded from: hufu-online-task-client.jar:BOOT-INF/classes/com/xuelangyun/util/AnalysisUtil.class */
public class AnalysisUtil {
    private static final Logger log = LoggerFactory.getLogger(AnalysisUtil.class);

    public static List<List> callJSFunction(String js, String json) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Object res = null;
        try {
            engine.eval(js);
            res = ((Invocable) engine).invokeFunction("parseJson", new Object[]{json});
        } catch (NoSuchMethodException e) {
            log.error("函数名必须定义:parseJson");
        } catch (ScriptException e2) {
            log.error(e2.getMessage());
        }
        List<List> lists = analysisJsObj(res);
        List fieldName = lists.get(0);
        List<String> fieldNameTrim = Lists.newArrayList();
        fieldName.forEach(
            item -> {
                trimFirstAndLastChar((String) item, "'");
                fieldNameTrim.add(trimFirstAndLastChar((String) item, "\""));
            });
        lists.remove(0);
        lists.add(0, fieldNameTrim);
        return lists;
    }

    public static List<List> analysisJsObj(Object o) {
        ArrayList<List> result = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : ((ScriptObjectMirror) o).entrySet()) {
            entry.getKey();
            ScriptObjectMirror inner = (ScriptObjectMirror) entry.getValue();
            ArrayList<Object> node = Lists.newArrayList();
            inner.forEach(
                (m, n) -> {
                    Object obj = JSON.toJSON(n);
                    if (obj instanceof String) {
                        String s = obj.toString();
                        if (s.startsWith("\"") && s.endsWith("\"")) {
                            s = s.substring(1, s.length() - 1);
                        }
                        obj = s;
                    }
                    node.add(obj);
                });
            result.add(node);
        }
        return result;
    }

    public static String trimFirstAndLastChar(String str, String element) {
        while (true) {
            str =
                str.substring(
                    str.indexOf(element) == 0 ? 1 : 0,
                    str.lastIndexOf(element) + 1 == str.length()
                        ? str.lastIndexOf(element)
                        : str.length());
            boolean beginIndexFlag = str.indexOf(element) == 0;
            boolean endIndexFlag = str.lastIndexOf(element) + 1 == str.length();
            if (!beginIndexFlag && !endIndexFlag) {
                return str;
            }
        }
    }

    public static void main(String[] args) {
        String jsScript = "function parseJson(inputParam) {\n" +
            "  // inputParam为返回报文的JSON字符串\n" +
            "  var dataObj = JSON.parse(inputParam)\n" +
            "  var result=[['name','value','time']]  // 定义参数名\n" +
            "  for(i=0; i < dataObj.values.length; i++) {  // 此处输入处理逻辑,以循环遍历为例\n" +
            "      var arr = []\n" +
            "      var name = dataObj.values[i].name  // 输入叶子节点数据\n" +
            "      var value = dataObj.values[i].value  // 输入叶子节点数据\n" +
            "      var time = dataObj.values[i].properties.updatetime  // 输入叶子节点数据\n" +
            "      time = time.replace(' ', 'T') + 'Z'\n" +
            "      time = new Date(time).getTime() + ''\n" +
            "      arr.push(\"abc\")\n" +
            "      arr.push(345.12)\n" +
            "      arr.push(time)\n" +
            "      result.push(arr)\n" +
            "  }\n" +
            "   return result\n" +
            "}";
        String json = "{\n" +
            "  \"values\": [\n" +
            "    {\n" +
            "      \"name\": \"name1\",\n" +
            "      \"value\": 1,\n" +
            "      \"properties\": {\n" +
            "        \"updatetime\": \"2021-01-01 00:00:00\"\n" +
            "      }\n" +
            "    },\n" +
            "    {\n" +
            "      \"name\": \"name2\",\n" +
            "      \"value\": 2,\n" +
            "      \"properties\": {\n" +
            "        \"updatetime\": \"2021-01-02 00:00:00\"\n" +
            "      }\n" +
            "    },\n" +
            "    {\n" +
            "      \"name\": \"name3\",\n" +
            "      \"value\": 3,\n" +
            "      \"properties\": {\n" +
            "        \"updatetime\": \"2021-01-03 00:00:00\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

        List<List> lists = callJSFunction(jsScript, json);
        System.out.println("lists = " + lists);
    }
}
